package com.ai.wxy.spring.jpa.sys.service;

import com.ai.spring.common.annotation.AddGroup;
import com.ai.spring.common.annotation.EditGroup;
import com.ai.spring.common.enums.DataStatusEnum;
import com.ai.spring.common.enums.ExceptionEnum;
import com.ai.spring.common.exception.ServiceException;
import com.ai.spring.common.util.IdWorker;
import com.ai.wxy.spring.jpa.sys.convert.SysConfDTOConvert;
import com.ai.wxy.spring.jpa.sys.dao.SysConfDao;
import com.ai.wxy.spring.jpa.sys.dto.SysConfDTO;
import com.ai.wxy.spring.jpa.sys.entity.SysConf;
import com.ai.wxy.spring.service.api.dto.DefaultServiceParam;
import com.ai.wxy.spring.service.api.dto.DefaultServiceResult;
import com.ai.wxy.spring.service.api.dto.ServiceConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import java.util.List;

/**
 * 请求服务接口配置服务
 *
 * @author 石头
 * @Date 2019/11/21
 * @Version 1.0
 **/
@Service("servicesConfig")
public class SysConfService implements ISysConfService{
    @Autowired
    private SysConfDao sysConfDao;
    @Autowired
    private SysConfDTOConvert convert;

    public DefaultServiceResult<Long> addSysConf(@Validated(value = AddGroup.class) SysConfDTO sysConfDTO){
        SysConf sysConf = convert.toEntity(sysConfDTO);
        sysConf.setSysCode(CODE_PREFIX+ IdWorker.getIdStr());
        sysConf = sysConfDao.save(sysConf);

        return DefaultServiceResult.build(sysConf.getId());
    }

    public DefaultServiceResult<SysConfDTO> updSysConf(@Validated(value = EditGroup.class) SysConfDTO sysConfDTO){
        SysConf sysConf = convert.toEntity(sysConfDTO);
        sysConf = sysConfDao.updateBySenstive(sysConf);

        return DefaultServiceResult.build(convert.toDto(sysConf));
    }

    public DefaultServiceResult<Boolean> delSysConf(DefaultServiceParam<Long> confId){
        if (confId == null || confId.getParam() == null){
            throw new ServiceException(ExceptionEnum.PARAM_ID_EXIST,"配置");
        }
        Boolean result = sysConfDao.removeById(confId.getParam());
        return DefaultServiceResult.build(result);
    }

    public ServiceConf getServiceConfByReqId(DefaultServiceParam<String> reqId){
        if (reqId == null || reqId.getParam() == null){
            throw new ServiceException(ExceptionEnum.PARAM_NO_EXIST,"请求编码");
        }
        SysConf query = new SysConf();
        query.setSysCode(reqId.getParam());
        query.setStatus(DataStatusEnum.VALID.getCode());
        List<SysConf> sysConfList = sysConfDao.findBySenstive(query);
        if (CollectionUtils.isEmpty(sysConfList)){
            return null;
        }

        return convert.toServiceConf(sysConfList.get(0));

    }
}
